package cn.xuqiudong.rpc.protocol.netty;

import cn.xuqiudong.rpc.protocol.netty.handler.XqdServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.DefaultThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.xuqiudong.rpc.cluster.exception.XqdCommonException;


/**
 * 描述: 服务提供端的netty服务
 * @author Vic.xu
 * @date 2022-02-18 10:59
 */
public class XqdNettyServer {


    private static Logger logger = LoggerFactory.getLogger(XqdNettyServer.class);

    /**
     * netty server bootstrap.
     */
    private ServerBootstrap bootstrap;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    /**
     * netty port
     */
    private int serverPort;

    public XqdNettyServer(int serverPort) {
        this.serverPort = serverPort;
    }


    public void start() {
        logger.info("NettyServer  start...");
        bootstrap = new ServerBootstrap();
        bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
        workerGroup = new NioEventLoopGroup(4, new DefaultThreadFactory("NettyServerWorker", true));
        try {

            bootstrap.group(bossGroup, workerGroup)
                    //非阻塞模式
                    .channel(NioServerSocketChannel.class)
                    // BACKLOG用于构造服务端套接字ServerSocket对象，标识当服务器请求处理线程全满时，用于临时存放已完成三次握手的请求的队列的最大长度。
                    // 如果未设置或所设置的值小于1，Java将使用默认值50。
                    //.option(ChannelOption.SO_BACKLOG, 128)
                    .childHandler(new XqdServerInitializer());
            ChannelFuture channelFuture = bootstrap.bind(this.serverPort).sync();
            logger.info("netty Server started Success on Port:{}", this.serverPort);
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            throw new XqdCommonException("netty server start failed", e);
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

}
